import { Compilation, Compiler, sources } from "webpack";
export class AutoJsRhino {
    constructor(
        private UIScriptList: string[]
    ) { }

    hasAsset(asset: string, filter: (a: string, b: string) => boolean) {
        let hasAsset = false;
        this.UIScriptList.map(script => {
            const res = filter(script, asset)
            if (res) hasAsset = true;
        })
        return hasAsset
    }
    apply(compiler: Compiler) {
        compiler.hooks.compilation.tap('AutoJsRhino', (compilation, normalModuleFactory) => {
            compilation.hooks.processAssets.tap({
                name: 'AutoJsRhino',
                stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
            }, (assets) => {
                for (const asset in assets) {
                    const isUi = this.hasAsset(asset, (a, b) => {
                        return b.startsWith(a)
                    })
                    if (isUi) {
                        compilation.updateAsset(asset, source => {
                            return new sources.ConcatSource(
                                `"rhino";`,
                                '\n',
                                source.buffer().toString('utf8')
                            )
                        });
                    }
                }
            });
        });
    }
}